﻿using Base.Infrastructure.Dto.Request.Error;
using Base.Service.Interface;

namespace Base.Api.Admin.MiddleWare
{
    /// <summary>
    /// 异常处理中间件
    /// </summary>
    public class ExceptionMiddle
    {
        private readonly RequestDelegate _requestDelegate;
        private IErrorService _errorService;

        public ExceptionMiddle(RequestDelegate requestDelegate)
        {
            _requestDelegate = requestDelegate;
        }

        /// <summary>
        /// 异常处理
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public async Task Invoke(HttpContext httpcontext, IErrorService errorService)
        {
            _errorService = errorService;
            try
            {
                await _requestDelegate.Invoke(httpcontext);
            }
            catch (Exception ex)
            {
                _errorService.AddError(new ErrorRequestDto
                {
                    ip = "127.0.0.1",
                    message = ex.Message,
                    url = httpcontext.Request.Path,
                });
                await httpcontext.Response.WriteAsJsonAsync(new
                {
                    code = -500,
                    message = "custom error"
                });
            }
        }

    }
}
